import Vue from "vue";
import VueRouter from "vue-router";
import HomeView from "../views/HomeView.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "home",
    component: HomeView,
  },
  {
    path: "/about",
    name: "about",
    component: () => import("../views/AboutView.vue"),
    // beforeEnter(to, from, next) {
    //   if (localStorage.getItem("token")) {
    //     next();
    //   } else {
    //     next("/login");
    //   }
    // },
    //单个理由规则独享的守卫 独享守卫 只守卫这一个页面 跟第二种组件级类似
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/Login.vue"),
  },
];

const router = new VueRouter({
  routes,
});

router.beforeEach((to, from, next) => {
  // console.log(to);
  // console.log(from);
  // next();
  if (localStorage.getItem("token")) {
    next();
  } else {
    if (to.path == "/login") {
      next();
    } else {
      next("/login");
    }
    //在这里再加一层判断是因为 login页面也会被守卫 然后会出现死循环 所以 我们要判断 如果是login的情况就放行
  }
  //如果有token证明登陆了 就正常跳转 如果没有token 就是没登陆 直接跳转到登陆页面
});
//路由跳转之前 全局守卫守卫所有页面

export default router;
